package com.zhangtai.modules.controller.member;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.modules.controller.admin.JobController;
import com.zhangtai.modules.controller.aouthLogin.MemberLoginController;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.ImgUrlDao;
import com.zhangtai.modules.dao.RegularBpmDao;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeRecruitmentEntity;
import com.zhangtai.modules.entity.regular.RegularBpmEntity;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.employee.EmployeeRecruitmentService;
import com.zhangtai.modules.service.promotion.PromotionService;
import com.zhangtai.modules.service.regular.RegularBpmService;
import com.zhangtai.modules.vo.RegularBpmVo;
import com.zhangtai.modules.vo.RegularListVo;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("member")
@Api(tags="员工转正接口")
@Slf4j
public class MemberRegularController {
    @Autowired
    private MemberLoginController memberLoginController;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private JobController jobController;
    @Autowired
    private ImgUrlDao imgUrlDao;
    @Autowired
    private RegularBpmService regularBpmService;
    @Autowired
    private RegularBpmDao regularBpmDao;
    @Autowired
    private PromotionService promotionService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;

    @Autowired
    private EmployeeRecruitmentService employeeRecruitmentService;





    @GetMapping("/regular/getInfo")
    @ApiOperation(value="查询新员工转正信息")
    public R getRegularInfo(HttpServletRequest request) throws Exception {
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)){
            return R.error("请先登录");
        }
        Long oid = data.getLong("id"); //只能查询自己的信息

//        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);

//        只查询新员工
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(0);
        integers.add(1);
        integers.add(3);
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid", oid).in("is_reinstate", integers));


        if (ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.error("查询员工为空");
        }

        Date regularDay = employeeInfoEntity.getRegularDay();
        if (ObjectUtils.isEmpty(regularDay)){
            return R.ok();
        }
            Integer integer = DateUtils.daysBetween(new Date(), regularDay);

//        只显示转正前15天
        if (integer<=20){
            setName(employeeInfoEntity); //根据Id设置名称
            return R.ok(employeeInfoEntity);
        }else {
            return R.ok();
        }


    }

//    @GetMapping("/regular/getInfo/list")
//    @ApiOperation(value="查询自己的转正信息列表")
//    public R getRegularList(HttpServletRequest request) throws Exception {
//        JSONObject data = memberLoginController.getUserInfo(request).getData();
//        Long oid = data.getLong("id"); //只能查询自己的信息
//        List<RegularBpmEntity> regularBpmEntities = regularBpmDao.selectList(new QueryWrapper<RegularBpmEntity>().eq("oid", oid).eq("is_delete", 0).eq("regular_type", 1));
//
//        if (CollectionUtils.isEmpty(regularBpmEntities)){
//            return R.ok();
//        }
//
//        for (RegularBpmEntity regularBpmEntity : regularBpmEntities) {
//            setName(regularBpmEntity); //根据Id设置名称
//        }
//
//
//
//        return R.ok(regularBpmEntities);
//
//    }



    @PostMapping("/member/create")
    @ApiOperation(value="新员工转正申请发起")
    @Transactional
    public R updateRegular(@RequestBody @Valid RegularBpmVo regularBpmVo, HttpServletRequest request) throws Exception{
        JSONObject data = memberLoginController.getUserInfo(request).getData();
        Long oid = data.getLong("id");

        EmployeeInfoEntity entity = employeeInfoService.getByIdE(oid);
        if(ObjectUtils.isEmpty(entity)){
            return  R.error("员工信息不存在！");
        }
        entity.setTrainDate(regularBpmVo.getTraindate());
        entity.setTrainScore(regularBpmVo.getTrainscore());
        entity.setRegularRemark(regularBpmVo.getRegularRemark());


//        RegularBpmEntity regularBpmEntity = BeanUtilsMabach.doToDto(regularBpmVo, RegularBpmEntity.class);

//        setParam(oid, entity, regularBpmEntity); //封装基本信息
//
//        regularBpmEntity.setRegularDay(entity.getRegularDay()); //转正日期
//
//        regularBpmEntity.setCreateTime(new Date());



//        employeeInfoEntity.setRegularIsDone(0);  //默认为空，等bpm发起成功后再处理
//        employeeInfoEntity.setIsRegular(0);
//        employeeInfoEntity.setRegularBpmStatus(0);

//        保存附件
        List<String> urls = regularBpmVo.getUrls();

        if (!CollectionUtils.isEmpty(urls)){
            ArrayList<Long> eids = new ArrayList<>();
            for (String url : urls) {

                Long eid = snowflakeIdWorker.nextId();
                eids.add(eid);
                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
                imgUrlEntity.setId(eid);
                imgUrlEntity.setName("转正附件");
                imgUrlEntity.setCreateTime(new Date());
                imgUrlEntity.setUrl(url);
                imgUrlDao.insert(imgUrlEntity);
            }
            String s = eids.toString();
            entity.setRegularUrlIds(s);
        }
//        List<RegularBpmEntity> regularBpmEntities = regularBpmDao.selectList(new QueryWrapper<RegularBpmEntity>().eq("oid", oid).eq("is_delete", 0)
//                .orderByDesc("create_time"));
//
//        if (CollectionUtils.isEmpty(regularBpmEntities)){
//            regularBpmService.saveE(regularBpmEntity);
//        }else {
//            RegularBpmEntity bpmEntity = regularBpmEntities.get(0);
//            Long id = bpmEntity.getId();
//            regularBpmEntity.setId(id);
//            regularBpmService.updateByIdE(regularBpmEntity);
//        }

        employeeInfoService.updateByIdE(entity);

        //修改招聘数据
        if(!org.springframework.util.StringUtils.isEmpty(entity.getRecruitmentId())){
            EmployeeRecruitmentEntity employeeRecruitmentEntity =new EmployeeRecruitmentEntity();
            employeeRecruitmentEntity.setId(entity.getRecruitmentId());
            employeeRecruitmentEntity.setTrainDate(entity.getTrainDate());
            employeeRecruitmentEntity.setTrainScore(entity.getTrainScore());
            employeeRecruitmentEntity.setRegularRemark(entity.getRegularRemark());
            employeeRecruitmentEntity.setRegularUrlIds(entity.getRegularUrlIds());
            employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
        }

        return R.ok();

    }

    private void setParam(Long oid, EmployeeInfoEntity entity, RegularBpmEntity regularBpmEntity) {
        regularBpmEntity.setOid(oid);
        regularBpmEntity.setName(entity.getName());
        Date hiredate = entity.getHiredate();
        regularBpmEntity.setHiredate(hiredate); //入职日期
        Long orgId = entity.getOrgId();
        regularBpmEntity.setOrgId(orgId); //公司id
        Long unitId = entity.getUnitId();
        regularBpmEntity.setUnitId(unitId); //部门id
        Long jobId = entity.getJobId();
        regularBpmEntity.setJobId(jobId); //岗位id
        Long jobLevelId = entity.getJobLevelId();
        regularBpmEntity.setJobLevelId(jobLevelId); //职级
        Integer jobLevelType = entity.getJobLevelType();
        regularBpmEntity.setJobLevelType(jobLevelType); //职级类型
        String code = entity.getCode();
        regularBpmEntity.setCode(code); //工号
        Integer probationday = entity.getProbationday();
        regularBpmEntity.setProbationday(probationday); //试用期
    }

    @GetMapping("/member/getSelfInfo")
    @ApiOperation(value="查看360评分和工资")
    public R get360Score(Long oid){

        List<RegularBpmEntity> regularBpmEntities = regularBpmDao.selectList(new QueryWrapper<RegularBpmEntity>().eq("oid", oid).eq("is_delete", 0)
                .orderByDesc("create_time"));
        RegularBpmEntity regularBpmEntity = regularBpmEntities.get(0);
        setName(regularBpmEntity); //根据Id设置名称

        return R.ok(regularBpmEntity);
    }

//    @PostMapping("/management/regular")
//    @ApiOperation(value="管理晋级转正申请")
//    @Transactional
//    public R managementRegular(@RequestBody @Valid ManagementRegularVo managementRegularVo,HttpServletRequest request) throws Exception {
//        JSONObject data = memberLoginController.getUserInfo(request).getData();
//        Long oid = data.getLong("id");
//
//        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(oid);
//        if (ObjectUtils.isEmpty(employeeInfoEntity)){
//            return R.error("查询员工为空");
//        }
//        Long promotionId = managementRegularVo.getRelationId();
//        String remark = managementRegularVo.getRemark();
//        PromotionEntity promotionEntity = new PromotionEntity();
//        promotionEntity.setPromotionId(promotionId);
//        if (StringUtils.isEmpty(remark)){
//            promotionEntity.setRegularRemark(remark);
//            promotionService.updateByIdE(promotionEntity);
//        }
//
//
//        RegularBpmEntity regularBpmEntity = BeanUtilsMabach.doToDto(managementRegularVo, RegularBpmEntity.class);
//
//        regularBpmEntity.setRelationId(promotionId);
//
//        regularBpmEntity.setHiredate(employeeInfoEntity.getHiredate());
//        regularBpmEntity.setCreateTime(new Date());
//        regularBpmEntity.setRegularType(2); //2:管理晋级转正
//        regularBpmEntity.setOid(oid);
//
////        封装附件
//        List<String> urls = managementRegularVo.getUrls();
//        if (!CollectionUtils.isEmpty(urls)){
//            ArrayList<Long> longs = new ArrayList<>();
//            for (String url : urls) {
//                ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
//                Long l = snowflakeIdWorker.nextId();
//                longs.add(l);
//                imgUrlEntity.setId(l);
//                imgUrlEntity.setCreateTime(new Date());
//                imgUrlEntity.setUrl(url);
//            }
//            String s = longs.toString();
//            regularBpmEntity.setUrlIds(s);
//        }
//        regularBpmService.saveE(regularBpmEntity);
//        return R.ok();
//
//    }
    @GetMapping("/getManagementInfo/{id}")
    @ApiOperation("获取管理专转正信息")
    public R getManagementInfo(@PathVariable("id")Long id){
        RegularBpmEntity byIdE = regularBpmService.getByIdE(id);
        setParam(byIdE); //封装基本信息
        return R.ok(byIdE);
    }


    @PostMapping("/getRegularBpmList")
    @ApiOperation("干部转正考察期追踪列表")
    public R<PageResult<RegularBpmEntity>> getRegularBpmList(@RequestBody @Valid RegularListVo vo,HttpServletRequest request)throws Exception{
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        Long oid = userInfo.getLong("id");
        PageResult<RegularBpmEntity> result = regularBpmService.getRegularList(vo.getType(),vo.getStartTime(),vo.getName(),
                null,vo.getEndTime(),oid,true,null,vo.getRegularBpmStatus(),null,null,null,
                vo.getPageNum(),vo.getPageSize());
        List<RegularBpmEntity> list = result.getList();
        for (RegularBpmEntity regularBpmEntity : list) {

            setParam(regularBpmEntity); //封装基本信息
        }
        result.setList(list);

        return R.ok(result);
    }

    private void setParam(RegularBpmEntity regularBpmEntity) {
        Long beforeOrgId = regularBpmEntity.getBeforeOrgId();
        if (beforeOrgId!=null){
            String orgNameById = jobController.getOrgNameById(beforeOrgId);
            regularBpmEntity.setBeforeOrgName(orgNameById);
        }
        Long beforeUnitId = regularBpmEntity.getBeforeUnitId();
        if (beforeOrgId!=null){
            String beforeUnit = jobController.getOrgNameById(beforeUnitId);
            regularBpmEntity.setBeforeUnitName(beforeUnit);
        }
        Long beforeJobLevelId = regularBpmEntity.getBeforeJobLevelId();
        if (beforeJobLevelId!=null){
            String beforeJobLevel = jobController.getJobLevelNameById(beforeJobLevelId);
            regularBpmEntity.setBeforeJobLevel(beforeJobLevel);

        }
        Long beforeJobId = regularBpmEntity.getBeforeJobId();
        if (beforeJobId!=null){
            String jobName = jobController.getJobName(beforeJobId);
            regularBpmEntity.setBeforeJobName(jobName);
        }
        Long orgId = regularBpmEntity.getOrgId();
        if (orgId!=null){
            String orgNameById = jobController.getOrgNameById(orgId);
            regularBpmEntity.setOrgname(orgNameById);
        }
        Long unitId = regularBpmEntity.getUnitId();
        if (unitId!=null){
            String orgNameById = jobController.getOrgNameById(unitId);
            regularBpmEntity.setUnitname(orgNameById);
        }
        Long jobLevelId = regularBpmEntity.getJobLevelId();
        if (jobLevelId!=null){
            String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
            regularBpmEntity.setJobLevel(jobLevelNameById);
        }
        Long jobId = regularBpmEntity.getJobId();
        if (jobId!=null){
            String jobName = jobController.getJobName(jobId);
            regularBpmEntity.setJobname(jobName);
        }
    }


    private void setName(EmployeeInfoEntity employeeInfoEntity) {
        Long jobId = employeeInfoEntity.getJobId();
        if (jobId!=null){
            String jobName = jobController.getJobName(jobId);
            employeeInfoEntity.setJobname(jobName); //岗位
        }

        Long orgId = employeeInfoEntity.getOrgId();
        if (orgId!=null){
            String orgNameById = jobController.getOrgNameById(orgId);
            employeeInfoEntity.setOrgname(orgNameById); //公司
        }

        Long unitId = employeeInfoEntity.getUnitId();
        if (unitId!=null){
            String unit = jobController.getOrgNameById(unitId);
            employeeInfoEntity.setUnitname(unit); //部门
        }

        Long jobLevelId = employeeInfoEntity.getJobLevelId();
        if (jobLevelId!=null){
            String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
            employeeInfoEntity.setJobLevel(jobLevelNameById); //职级
        }
    }

    private void setName(RegularBpmEntity regularBpmEntity) {
        Long jobId = regularBpmEntity.getJobId();
        if (jobId!=null){
            String jobName = jobController.getJobName(jobId);
            regularBpmEntity.setJobname(jobName); //岗位
        }

        Long orgId = regularBpmEntity.getOrgId();
        if (orgId!=null){
            String orgNameById = jobController.getOrgNameById(orgId);
            regularBpmEntity.setOrgname(orgNameById); //公司
        }

        Long unitId = regularBpmEntity.getUnitId();
        if (unitId!=null){
            String unit = jobController.getOrgNameById(unitId);
            regularBpmEntity.setUnitname(unit); //部门
        }

        Long jobLevelId = regularBpmEntity.getJobLevelId();
        if (jobLevelId!=null){
            String jobLevelNameById = jobController.getJobLevelNameById(jobLevelId);
            regularBpmEntity.setJobLevel(jobLevelNameById); //职级
        }
    }
}
